package edu.thu.thss.yxy.gui;

import javax.swing.*;
import java.io.*;

public class ContactsComboBoxModel extends DefaultComboBoxModel {
	public ContactsComboBoxModel() {
		loadDialHistory();
	}

	private void loadDialHistory() {
		try {
			FileReader fReader = new FileReader("dialhistory.txt");
			BufferedReader dialHistory = new BufferedReader(fReader);
			String entry = null;
			while ((entry = dialHistory.readLine()) != null)
				super.insertElementAt(entry, 0);
			dialHistory.close();
			fReader.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public void addElement(Object element) {
		if (super.getIndexOf(element) != -1)
			return;
		if (element == null || element.toString().trim().length() == 0)
			return;
		try {
			FileWriter fWriter = new FileWriter("dialhistory.txt", true);
			PrintWriter dialHistory = new PrintWriter(fWriter);

			dialHistory.println(element.toString());

			dialHistory.close();
			fWriter.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		super.insertElementAt(element, 0);
	}
}